/**
 * Created with Vim7.3 ubuntu12.04
 * @fileOverview : 
 * @author : Lyle <lylechen2014@gmial.com>
 * @since : 2014-12-22 13:18:20
 * @filename : controller/aol_spam_by_title.js
 * @version : 
 * @description : 
 */

define(function(require, exports, module){

    require("pagination/jquery.pagination");
    require("pagination/pagination.css"); 

    var name = 'AOL Spam By template', mId = 'aol_spam_by_title',
        tpl = require('{view}page_email.tpl'),
        tplD = require('{view}page_email_desc_a.tpl'),
        tplH = require('{view}page_email_head.tpl'),
        tplT = require('{view}table.tpl'),
        tplS = require('{view}select.tpl');

    var tempOpt = {
            engine : '',
            begin_date : null,
            end_date : null,
            page : 1,
            offset : 13  
        };
 
    var AOLSpamBTView = Backbone.View.extend({

        initialize: function (obj) { 
            this.run(obj);
        },

        run : function(obj) {
            if ($('.main').length !== 3) { 
                Backbone.routerObj.navigate('index/w/'+mId, { trigger: true });return;
            } else {
                this.tplRender();
            }
        },

        tplRender : function() {
            if ($('#'+mId).length < 1) { 
                $('#index_right').append(_.template(tpl)({obj:{name:name,mId:mId}}));
                $('#'+mId).find('.m_head').append(_.template(tplH));
                this.defaultOpt();
                this.afterBindEvt();
                this.fetchData(tempOpt); 
            } else {
                $('#'+mId).css('display','block');
            } 
        },

        afterBindEvt : function() {
            var tthis = this,dom = $('#'+mId);

            new Pikaday({
                field: dom.find('.from_time')[0],
                firstDay: 1,
                minDate: new Date('1997-01-01'),
                maxDate: new Date('2020-12-31'),
                yearRange: [1997,2020]
            });

            new Pikaday({
                field: dom.find('.to_time')[0],
                firstDay: 1,
                minDate: new Date('1997-01-01'),
                maxDate: new Date('2020-12-31'),
                yearRange: [1997,2020]
            });

            dom.find('.selectTime').on('change',function(){
                var val = $(this).val();
                    share.setInputDate(val,mId);
            });


            dom.find('.do').on('click',function(){
                var obj = tthis.getPostData(); 
                if (obj) { 
                    tthis.fetchData(obj);
                }
            });

            dom.find('.m_head').find('input[type="text"]').on('focus',function(){
                $('#'+mId).find('.selectTime').find("option[value='']").attr("selected",true); 
            });
        },

        defaultOpt : function() {
            var dom = $('#'+mId);
            this.selectSite();
            share.setInputDate('last-week',mId);
            tempOpt.end_date = dom.find('.to_time').val();
            tempOpt.begin_date = dom.find('.from_time').val(); 
            tempOpt.engine = '';
        },
 
        selectSite : function() {
             var siteInfo =  share.getAllSites(1);
             $('#'+mId).find('.selectInfo').html(_.template(tplS)({obj:siteInfo}));
        },

        getPostData : function() {
            var dom = $('#'+mId);
            tempOpt.engine = dom.find('.selectInfo').find('select').val();
            if (tempOpt.engine == '0') { tempOpt.engine = ''};
            tempOpt.end_date = dom.find('.to_time').val();
            tempOpt.begin_date = dom.find('.from_time').val();
            tempOpt.page = 1;

            if (tempOpt.end_date == '' || tempOpt.begin_date == '') {
                alert('The time is required!');
                return false;
            }
            if (new Date(tempOpt.end_date) < new Date(tempOpt.begin_date)) {
                alert('The end time is less than the start time!');
                return false;
            }
            if (new Date(tempOpt.end_date) > new Date()) {
                alert('The end time is greater than the current time!');
                return false;
            }
            return tempOpt;
        }, 

        fetchData : function(data) {
            var tthis = this,
                ajaxOpt = {
                url : seajs.data.vars.apiUrl+ ((data.engine == '') ? 'email_tpl_status' : 'email_tpl_status_site'),
                type : 'POST',
                data : data,
                success : function(data) {
                    console.log(data);
                    tthis.fetchSuccess(data);
                    tthis.pagination(data);
                },
                error : function(xhr, errorType, error) {
                },
                complete : function(xhr,status){
                    share.load($('#'+mId),false); 
                }
            };

            share.load($('#'+mId),true); 
            share.ajax(ajaxOpt,true);
        },

        pagination : function(data) {
            var tthis = this;
            new $.fn.pagination({
                dom : $('#'+mId).find(".pagination"),
                total_num : parseInt(data.total), 
                num_edge_entries: 1, 
                current_page:tempOpt.page,
                num_display_entries: 4, 
                items_per_page:tempOpt.offset,
                callback : function(current){
                    tempOpt.page = current;
                    tthis.fetchData(tempOpt);
                }
            });
        },

        fetchSuccess : function(data) {
            //add main gold
            this.details(data);
        },

        details : function(data) {
            var arr = [];
            arr.push({name:'Project',val:'NAME'});
            arr.push({name:'Email template',val:'ORIG_TEMPLATE'});
            arr.push({name:'Number ',val:'CNT'});

            var total = {};
                total.BEING_DATE = tempOpt.begin_date;
                total.END_DATE = tempOpt.end_date;
                total.SITE = share.getSiteName(tempOpt.engine);
                total.MES_TATOL =  data.total ? Number(data.total) : 0;

            $('#'+mId).find('.desc').html(_.template(tplD)({obj:total}));
            $('#'+mId).find('.table').html(_.template(tplT)({obj:data.data,arr:arr}));

        }

    });
    module.exports = AOLSpamBTView;
});

